<?php

namespace App\Model;

use Zizaco\Entrust\EntrustPermission;

/**
 * App\Model\Premission
 *
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Model\Role[] $roles
 * @mixin \Eloquent
 * @property integer $id
 * @property string $name
 * @property string $display_name
 * @property string $description
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Permission whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Permission whereName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Permission whereDisplayName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Permission whereDescription($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Permission whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Model\Permission whereUpdatedAt($value)
 */
class Permission extends EntrustPermission
{
    protected $guarded = [];

    public function permissionRoles()
    {
        return $this->hasMany(PermissionRole::class, 'permission_id');
    }

    /**
     * 选择出所有该权限的管理员
     *
     * @return \Illuminate\Support\Collection
     */
    public function admins()
    {
        $admins = collect();

        $this->roles->each(function($role) use ($admins){
            $role->users->each(function($user) use ($admins){
                $admins->push($user);
            });
        });

        return $admins;
    }

    /**
     * 选择出所有该权限的用户
     *
     * @return \Illuminate\Support\Collection
     */
    public function users()
    {
        $users = collect();

        $this->admins()->each(function($admin) use ($users){
            $users->push($admin->user);
        });

        return $users;
    }
}
